package service

import (
	"context"
	"errors"
	pb "medicine/api/medicine/v1"
	"medicine/internal/biz"
)

type SeckillOrderService struct {
	pb.UnimplementedSeckillOrderServer // 必须嵌入，满足 gRPC 接口要求
	Souc                               *biz.SeckillOrderUsecase
}

func NewSeckillOrderService(souc *biz.SeckillOrderUsecase) *SeckillOrderService {
	return &SeckillOrderService{Souc: souc}
}

// ListSeckillOrder 获取订单列表，分页参数支持默认值
func (s *SeckillOrderService) ListSeckillOrder(ctx context.Context, req *pb.ListSeckillOrderRequest) (*pb.ListSeckillOrderReply, error) {
	page := int(req.Page)
	if page <= 0 {
		page = 1
	}
	pageSize := int(req.PageSize)
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 20
	}
	orders, total, err := s.Souc.List(ctx, req.UserId, page, pageSize)
	if err != nil {
		return nil, err
	}
	var pbOrders []*pb.SeckillOrderReply
	for _, o := range orders {
		pbOrders = append(pbOrders, &pb.SeckillOrderReply{
			Id:               o.ID,
			UserId:           o.UserID,
			SeckillProductId: o.SeckillProductID,
			ProductId:        o.ProductID,
			SeckillPrice:     o.SeckillPrice,
			Quantity:         int32(o.Quantity),
			Status:           o.Status,
			OrderNo:          o.OrderNo,
			TotalPrice:       o.TotalPrice,
			CreatedAt:        o.CreatedAt.Format("2006-01-02 15:04:05"),
			PaidAt:           o.PaidAt.Format("2006-01-02 15:04:05"),
		})
	}
	return &pb.ListSeckillOrderReply{
		Orders: pbOrders,
		Total:  int32(total),
	}, nil
}

// GetSeckillOrder 获取订单详情
func (s *SeckillOrderService) GetSeckillOrder(ctx context.Context, req *pb.GetSeckillOrderRequest) (*pb.SeckillOrderReply, error) {
	o, err := s.Souc.Get(ctx, req.Id)
	if err != nil {
		return nil, err
	}
	return &pb.SeckillOrderReply{
		Id:               o.ID,
		UserId:           o.UserID,
		SeckillProductId: o.SeckillProductID,
		ProductId:        o.ProductID,
		SeckillPrice:     o.SeckillPrice,
		Quantity:         int32(o.Quantity),
		Status:           o.Status,
		OrderNo:          o.OrderNo,
		TotalPrice:       o.TotalPrice,
		CreatedAt:        o.CreatedAt.Format("2006-01-02 15:04:05"),
		PaidAt:           o.PaidAt.Format("2006-01-02 15:04:05"),
	}, nil
}

// CreateSeckillOrder 创建订单
func (s *SeckillOrderService) CreateSeckillOrder(ctx context.Context, req *pb.CreateSeckillOrderRequest) (*pb.CreateSeckillOrderReply, error) {
	order := &biz.SeckillOrder{
		UserID:           req.UserId,
		SeckillProductID: req.SeckillProductId,
		Quantity:         int(req.Quantity),
		Status:           "待支付",
	}
	newOrder, payUrl, err := s.Souc.Create(ctx, order)
	if err != nil {
		return nil, err
	}
	return &pb.CreateSeckillOrderReply{
		OrderId:    newOrder.ID,
		PayUrl:     payUrl,
		OrderNo:    newOrder.OrderNo,
		TotalPrice: newOrder.TotalPrice,
	}, nil
}

// GetPayURL 获取订单支付链接
func (s *SeckillOrderService) GetPayURL(ctx context.Context, req *pb.GetPayURLRequest) (*pb.GetPayURLReply, error) {
	order, err := s.Souc.GetByOrderNo(ctx, req.OrderNo)
	if err != nil || order == nil {
		return nil, err
	}
	if order.Status != "待支付" {
		return nil, errors.New("订单状态不支持支付")
	}
	payUrl := ""
	alipay := s.Souc.GetAlipayService()
	if alipay != nil {
		payUrl, err = alipay.GeneratePayURL(ctx,
			order.OrderNo,
			"秒杀订单支付",
			order.TotalPrice,
		)
		if err != nil {
			return nil, err
		}
	}
	return &pb.GetPayURLReply{PayUrl: payUrl}, nil
}
